package com.mjk.manager.api.apipost;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;

import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.annotation.BeeApi;
import com.mjk.common.core.jdbc.annotation.Filed;
import com.mjk.common.core.jdbc.bean.BeePage;
import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.*;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.manager.api.constns.ApiPostProperties;
import com.mjk.manager.api.dto.ApiFieldEntity;
import com.mjk.manager.api.dto.ApiPostRequest;
import com.mjk.manager.api.model.ApiModel;
import org.apache.commons.collections.MapUtils;
import org.springframework.util.CollectionUtils;

public class ApiPostUtils {
	/**
	 * 是否推送
	 */
	public static final String APIPOST_PUSH = "1";
	/**
	 * response转参数
     */
	public static List<ApiPostRequest.Parameter> response2Parameter(BeeResponse rsp){
		List<ApiPostRequest.Parameter> rspParameter = new ArrayList<>();
		ApiPostRequest.Parameter param = new ApiPostRequest.Parameter();
		param.setKey("code");
		param.setDescription("错误码");
		param.setIs_checked("1");
		param.setType("Number");
		rspParameter.add(param);
		ApiPostRequest.Parameter param1 = new ApiPostRequest.Parameter();
		param1.setKey("msg");
		param1.setIs_checked("1");
		param1.setDescription("错误说明");
		param1.setType("String");
		rspParameter.add(param1);
		if(rsp.getData() instanceof Map map) {
			rspParameter.addAll(map2Parameter("data.", map));
		}else if(rsp.getData() instanceof List list) {
			rspParameter.addAll(list2Parameter("data.", list));
		}else if(rsp.getData() instanceof BaseEntity entity) {
			rspParameter.addAll(baseEntity2Parameter("data.", entity));
		}else if(rsp.getData() instanceof BeePage page) {
			rspParameter.addAll(list2Parameter("data.",page.getList()));
		}
		return rspParameter;
	}
	/**
	 * list转参数
     */
	public static List<ApiPostRequest.Parameter> list2Parameter(String title,List list){
		List<ApiPostRequest.Parameter> rspParameter = new ArrayList<>();
		if(!CollectionUtils.isEmpty(list)) {
			Object obj = list.get(0);
			if(obj instanceof BaseEntity entity) {
				rspParameter.addAll(baseEntity2Parameter(title ,entity));
			}else if (obj instanceof Map map) {
				rspParameter.addAll(map2Parameter(title,map));
			}else if(obj instanceof List list1) {
				rspParameter.addAll(list2Parameter(title,list1));
			}
		}
		return rspParameter;
	}
	/**
	 * map转参数
     */
	public  static List<ApiPostRequest.Parameter> map2Parameter(String title,Map map){
		Set keys = map.keySet();
		List<ApiPostRequest.Parameter> rspParameter = new ArrayList<>();
		for(Object key : keys) {
			if(ClassUtil.isBasicType(map.get(key).getClass())) {
				ApiPostRequest.Parameter param = new ApiPostRequest.Parameter();
				param.setKey(title+key.toString());
				param.setField_type(ApiPostProperties.ApiPostTypeTransferEnum.transferType(key.getClass()));
				param.setIs_checked("1");
				rspParameter.add(param);
			}else {
				if(map.get(key) instanceof BaseEntity entity) {
					rspParameter.addAll(baseEntity2Parameter(title+key.toString()+"." ,entity));
				}else if (map.get(key) instanceof Map map1) {
					rspParameter.addAll(map2Parameter(title+key.toString()+".",map1));
				}else if(map.get(key) instanceof List list) {
					rspParameter.addAll(list2Parameter(title+key.toString()+".",list));
				}
			}
		}
		return rspParameter;
	}
	/**
	 * BaseEntity转参数
     */
	public  static List<ApiPostRequest.Parameter> baseEntity2Parameter(String title,BaseEntity entity) {
		List<ApiPostRequest.Parameter> rspParameter = new ArrayList<>();
		Field[] fields = entity.getClass().getDeclaredFields();
		for(Field f : fields) {
			ApiPostRequest.Parameter param = new ApiPostRequest.Parameter();
			Filed filed = f.getAnnotation(Filed.class);
			param.setKey(title+f.getName());
			if(null != filed) {
				param.setDescription(filed.comment());
			}
			param.setField_type(ApiPostProperties.ApiPostTypeTransferEnum.transferType(f.getType()));
			param.setIs_checked("1");
			rspParameter.add(param);
		}
		return rspParameter;
	}
	
	/**
	 * 创建接口
     */
	public static ApiPostRequest buildApiPostRequest(ApiModel model, BeeResponse rsp, ApiPostProperties properties) {
		ApiPostRequest req = new ApiPostRequest();
		req.setTarget_id( model.getMenuId());
		req.setParent_id(model.getModelId());
		req.setProject_id(properties.getProjectId());
		req.setName(model.getApiName());
		
		ApiPostRequest.Request request = new ApiPostRequest.Request();
		request.setUrl(model.getUrl());
		ApiPostRequest.Body body = new ApiPostRequest.Body();
		request.setBody(body);
		ApiPostRequest.Query query = new ApiPostRequest.Query();
		List<ApiFieldEntity> fileds = GsonUtils.json2List(model.getParams(), ApiFieldEntity.class);
		List<ApiPostRequest.Parameter> reqParameter = new ArrayList<>();
		if(!CollectionUtils.isEmpty(fileds)) {
			for(ApiFieldEntity field : fileds) {
				ApiPostRequest.Parameter param = new ApiPostRequest.Parameter();
				param.setKey(field.getField());
				param.setIs_checked("");
				param.setDescription(field.getRemark());
				param.setField_type(field.getType());
				reqParameter.add(param);
			}
		}
		query.setParameter(reqParameter);
		request.setQuery(query);
		req.setRequest(request);
		ApiPostRequest.Response rsponse = new ApiPostRequest.Response();
		ApiPostRequest.Success suc = new ApiPostRequest.Success();
		suc.setRaw("");
		suc.setParameter(ApiPostUtils.response2Parameter(rsp));
		rsponse.setSuccess(suc);
		req.setResponse(rsponse);
		return req;
	}
	/**
	 * 初始化入参
     */
    public static List<ApiFieldEntity> getApiFieldList(Object work, GetWayInterceptorReq req, ApiModel model) {
		List<ApiFieldEntity> fileds = new ArrayList<>();
		java.lang.reflect.Parameter clazz = null;
		if(null != work) {
			Method m = ReflectionUtils.getMethod(work.getClass(), MapUtils.getString(req.getParams(), GetwayConsts.METHOD));
			if(null != m) {
				clazz = m.getParameters()[0];
				if(ObjectUtils.isEmpty(model.getId())) {
					BeeApi api =  m.getAnnotation(BeeApi.class);
					if(api!=null) {
						model.setApiName(api.name());
					}else {
						model.setApiName(work.getClass().getSimpleName() + "." + m.getName());
					}
				}
			}
		}
        List<String> filters = Arrays.asList("method", "work", "ip", "mappingversion", "protocal", "version");
		List<ApiFieldEntity> params = GsonUtils.json2List(model.getParams() ,ApiFieldEntity.class) ;
		if(CollectionUtils.isEmpty(params)) {
			for(Entry<String,Object> entry : req.getParams().entrySet()) {
				if(!filters.contains(entry.getKey())) {
					ApiFieldEntity entity = new ApiFieldEntity();
					entity.setField(entry.getKey());
					//获取说明
					if(null != clazz) {
						try {
							Field f = clazz.getType().getDeclaredField(entry.getKey());
                            Filed filed = f.getAnnotation(Filed.class);
                            if(null!=filed) {
                                entity.setRemark(filed.comment());
                            }
                        }catch(Exception e) {
                            //do noting
                        }
					}
					//默认都为字符类型
					entity.setType(String.class.getSimpleName());
					fileds.add(entity);
				}
			}
			return fileds;
		}else {
			return params;
		}
	}
	/**
	 * 发送接口到apipost
     */
	public static void send2ApiPost(ApiPostRequest req,ApiPostProperties properties) {
		Map<String,String> header = new HashMap<>();
		header.put("api-token", properties.getApiToken());
		header.put("content-type", "application/json");
		String result = HttpUtils.httpPost(properties.getUrl(), GsonUtils.bean2Json(req), header);
		BizLogger.info(result);
	}
}
